using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 页面管理接口
    /// 提供页面的增删改查、发布、层级管理等功能的 RESTful API
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class PagesController : ControllerBase
    {
        private readonly IPageAppService _pageService;
        private readonly ILogger<PagesController> _logger;

        public PagesController(
            IPageAppService pageService,
            ILogger<PagesController> logger)
        {
            _pageService = pageService;
            _logger = logger;
        }

        /// <summary>
        /// 分页获取页面列表
        /// </summary>
        /// <returns>页面分页结果</returns>
        [HttpGet]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<PagedResultDto<PageDto>>> GetPaged(
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20,
            [FromQuery] string? keyword = null,
            [FromQuery] byte? status = null)
        {
            try
            {
                var (items, total) = await _pageService.GetPagedAsync(pageIndex, pageSize, keyword, status);
                return Ok(new PagedResultDto<PageDto>(items, total, pageIndex, pageSize));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting paged pages");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 获取所有页面
        /// </summary>
        /// <returns>页面列表</returns>
        [HttpGet("all")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<IEnumerable<PageDto>>> GetAll()
        {
            try
            {
                var result = await _pageService.GetAllAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all pages");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取页面
        /// </summary>
        /// <param name="id">页面ID</param>
        /// <returns>页面详情</returns>
        [HttpGet("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        [AllowAnonymous]
        public async Task<ActionResult<PageDto>> GetById(long id)
        {
            try
            {
                var result = await _pageService.GetByIdAsync(id);
                if (result == null) return NotFound();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting page {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 根据slug获取页面
        /// </summary>
        /// <param name="slug">页面slug</param>
        /// <returns>页面详情</returns>
        [HttpGet("slug/{slug}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        [AllowAnonymous]
        public async Task<ActionResult<PageDto>> GetBySlug(string slug)
        {
            try
            {
                var result = await _pageService.GetBySlugAsync(slug);
                if (result == null) return NotFound();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting page by slug {Slug}", slug);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 获取子页面列表
        /// </summary>
        /// <param name="parentId">父页面ID</param>
        /// <returns>子页面列表</returns>
        [HttpGet("{parentId:long}/children")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<IEnumerable<PageDto>>> GetChildren(long parentId)
        {
            try
            {
                var result = await _pageService.GetChildrenAsync(parentId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting children for page {ParentId}", parentId);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 获取导航页面
        /// </summary>
        /// <returns>导航页面列表</returns>
        [HttpGet("navigation")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<IEnumerable<PageDto>>> GetNavigation()
        {
            try
            {
                var result = await _pageService.GetNavigationPagesAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting navigation pages");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 获取页面层级结构
        /// </summary>
        /// <returns>页面层级结构</returns>
        [HttpGet("hierarchy")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<IEnumerable<PageDto>>> GetHierarchy()
        {
            try
            {
                var result = await _pageService.GetHierarchyAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting page hierarchy");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 创建页面
        /// </summary>
        /// <param name="dto">页面数据</param>
        /// <returns>创建的页面</returns>
        [HttpPost]
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<PageDto>> Create([FromBody] PageDto dto)
        {
            try
            {
                var created = await _pageService.CreateAsync(dto);
                return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating page");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 更新页面
        /// </summary>
        /// <param name="id">页面ID</param>
        /// <param name="dto">页面数据</param>
        /// <returns>更新后的页面</returns>
        [HttpPut("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<PageDto>> Update(long id, [FromBody] PageDto dto)
        {
            try
            {
                dto.Id = id;
                var updated = await _pageService.UpdateAsync(dto);
                return Ok(updated);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating page {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 删除页面
        /// </summary>
        /// <param name="id">页面ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<object>> Delete(long id)
        {
            try
            {
                var ok = await _pageService.DeleteAsync(id);
                if (!ok) return NotFound();
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting page {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除页面
        /// </summary>
        /// <param name="request">批量删除请求</param>
        /// <returns>删除结果</returns>
        [HttpPost("batch-delete")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> BatchDelete([FromBody] BatchDeleteRequest request)
        {
            try
            {
                var count = await _pageService.BatchDeleteAsync(request.Ids);
                return Ok(new { success = true, count });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error batch deleting pages");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 更新页面状态
        /// </summary>
        /// <param name="id">页面ID</param>
        /// <param name="status">页面状态</param>
        /// <returns>更新结果</returns>
        [HttpPost("{id:long}/status")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> UpdateStatus(long id, [FromQuery] byte status)
        {
            try
            {
                var ok = await _pageService.UpdateStatusAsync(id, status);
                return Ok(new { success = ok });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating page status {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 增加页面访问量
        /// </summary>
        /// <param name="id">页面ID</param>
        /// <returns>操作结果</returns>
        [HttpPost("{id:long}/views/increment")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<object>> IncrementViews(long id)
        {
            try
            {
                var ok = await _pageService.IncrementViewCountAsync(id);
                return Ok(new { success = ok });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error incrementing page views {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 检查slug是否存在
        /// </summary>
        /// <param name="slug">页面slug</param>
        /// <param name="excludeId">排除的页面ID</param>
        /// <returns>检查结果</returns>
        [HttpGet("slug-exists")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> SlugExists([FromQuery] string slug, [FromQuery] long? excludeId = null)
        {
            try
            {
                var exists = await _pageService.SlugExistsAsync(slug, excludeId);
                return Ok(new { exists });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error checking slug exists {Slug}", slug);
                return BadRequest(new { message = ex.Message });
            }
        }
    }
}
